package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.rabbit.RabbitArticleDownOrUpConstants;
import com.heima.common.constants.rabbit.RabbitArticlePublishConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.constants.wemedia.WemediaNewsAutoScanConstants;
import com.heima.common.exception.CustomizeExceptionBuilder;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsReviewDTO;
import com.heima.model.wemedia.dtos.WmNewsSaveDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.vos.WmNewsReviewVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.IWmNewsService;
import io.seata.common.util.CollectionUtils;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.bind.Element;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsService extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 分页模糊查询文章列表
     * @param wmNewsDTO
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsDTO wmNewsDTO) {
        //1.校验参数
            //1.1校验分页参数
        wmNewsDTO.checkParam();
            //1.2校验登录
        Integer userId = WmThreadLocalUtils.getUser();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "操作受限，请先登录");
        }
        //2.查询自媒体文章列表
            //2.1封装分页条件
        IPage<WmNews> pageQuery = new Page<>(wmNewsDTO.getPage(), wmNewsDTO.getSize());
            //2.2封装模糊查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
                //2.2.1关键字不为空时，根据其模糊查询文章标题
        if(StringUtils.isNotBlank(wmNewsDTO.getKeyword())){
            queryWrapper.like(WmNews::getTitle, wmNewsDTO.getKeyword());
        }
                //2.2.2频道 id 不为空
        if(wmNewsDTO.getChannelId() != null){
            queryWrapper.eq(WmNews::getChannelId, wmNewsDTO.getChannelId());
        }
                //2.2.3文章状态不为空
        if(wmNewsDTO.getStatus() != null){
            queryWrapper.eq(WmNews::getStatus, wmNewsDTO.getStatus());
        }
                //2.2.4创建文章时间区间不为空
        if(wmNewsDTO.getBeginPubDate() != null && wmNewsDTO.getEndPubDate() != null){
            queryWrapper.between(WmNews::getCreatedTime, wmNewsDTO.getBeginPubDate(), wmNewsDTO.getEndPubDate());
        }
                //2.2.5查询当前登录用户发布的文章
        queryWrapper.eq(WmNews::getUserId, userId);
        //2.3封装排序方式
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        IPage<WmNews> pageResult = this.page(pageQuery, queryWrapper);
        //3.响应结果
        PageResponseResult pageResponseResult = new PageResponseResult(wmNewsDTO.getPage(), wmNewsDTO.getSize(), pageResult.getTotal());
            //3.1需要返回文章图片的前缀
        pageResponseResult.setHost(webSite);
        pageResponseResult.setData(pageResult.getRecords());
        return pageResponseResult;
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 保存或修改文章信息
     * @param wmNewsSaveDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult insertOrUpdateWmNews(WmNewsSaveDTO wmNewsSaveDTO) {
        //1.校验参数及封装文章 POJO
            //1.1校验参数内容、状态、是否登录
        if(wmNewsSaveDTO.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章内容不能为空");
        }
        if(!WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(wmNewsSaveDTO.getStatus()) && !WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNewsSaveDTO.getStatus())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章提交的状态不对");
        }
        Integer userId = WmThreadLocalUtils.getUser();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "操作受限，请先登录");
        }
            //1.2实体类封装
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsSaveDTO, wmNews);
        wmNews.setUserId(userId);
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsSaveDTO.getType())){
            wmNews.setType(null);
        }
        wmNews.setImages(convertImageStr(wmNewsSaveDTO.getImages()));
        //2.保存文章数据
        if(wmNews.getId() == null) {
            wmNews.setSubmittedTime(wmNews.getPublishTime());
            wmNews.setCreatedTime(new Date());
            this.save(wmNews);
        }else{
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            wmNews.setSubmittedTime(new Date());
            this.updateById(wmNews);
        }
        //3.保存文章(发布)与素材的关联关系，草稿不做处理
        if(WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNewsSaveDTO.getStatus())) {
            //3.1保存文章内容与素材的关联关系
            List<String> contentImages = resolveRelationForContent(wmNewsSaveDTO.getContent());
            if(CollectionUtils.isNotEmpty(contentImages)) {
                saveRelativeInfo(contentImages, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
            }
            //3.2保存文章封面与素材的关联关系
            resolveRelationForCover(wmNewsSaveDTO, wmNews, contentImages);
            //4.MQ 异步回调执行自动审核
            rabbitTemplate.convertAndSend(WemediaNewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
            log.info("文章自动审核消息成功发送，文章 id: {}，消息队列: {}", wmNews.getId(), WemediaNewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE);
        }
        //5.响应结果
        return ResponseResult.okResult();
    }

    /**
     * 根据 id 查询文章信息
     * @param id
     * @return
     */
    @Override
    public ResponseResult queryWmNewsById(Integer id) {
        //1.校验参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章 id 不能为空");
        }
        //2.查询文章信息
        WmNews wmNews = this.getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "WmNews 不存在");
        }
        //3.返回响应
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 根据 id 删除文章信息
     * @param id
     * @return
     */
    @Transactional
    @Override
    public ResponseResult deleteWmNewsById(Integer id) {
        //1.校验参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //2.删除文章信息
            //2.1判断文章状态，已发布并且已上架的文章不能删除
        if(WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus()) && WemediaConstants.WM_NEWS_UP.equals(wmNews.getEnable())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "已发布并上架的文章不能删除");
        }
            //2.2删除文章数据
        this.removeById(id);
            //2.3删除引用数据
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
        //3.返回响应
        return ResponseResult.okResult();
    }

    /**
     * 根据 id 修改文章的上下架状态
     * @param wmNewsSaveDTO
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult downOrUp(WmNewsSaveDTO wmNewsSaveDTO) {
        //1.校验参数
        if(wmNewsSaveDTO.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章 id 不能为空");
        }
        if(wmNewsSaveDTO.getEnable() == null || (!WemediaConstants.WM_NEWS_DOWN.equals(wmNewsSaveDTO.getEnable()) && !WemediaConstants.WM_NEWS_UP.equals(wmNewsSaveDTO.getEnable()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章的上下架状态值不对");
        }
        WmNews wmNews = this.getById(wmNewsSaveDTO.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //2.修改上下架状态
            //2.1只有文章状态是已发布时，才能修改文章的上下架状态
        if(!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章为发布，不能修改上下架状态");
        }
        wmNews.setEnable(wmNewsSaveDTO.getEnable());
        this.updateById(wmNews);
        //异步通知 ApArticleConfig 和 es 索引库中 ApArticle 的状态修改
        WmNewsDownOrUp(wmNews);
        //3.响应结果
        return ResponseResult.okResult();
    }

    /**
     * 异步通知 ApArticleConfig 和 es 索引库中 ApArticle 的状态修改
     * @param wmNews
     */
    private void WmNewsDownOrUp(WmNews wmNews) {
        if(WemediaConstants.WM_NEWS_DOWN.equals(wmNews.getEnable())){
            //下架
            rabbitTemplate.convertAndSend(RabbitArticleDownOrUpConstants.ARTICLE_DOWN_OR_UP_EXCHANGE,
                    RabbitArticleDownOrUpConstants.DOWN_ROUTING_KEY,
                    wmNews.getArticleId());
            log.info("WmNews 下载状态修改后，通知 ApArticleConfig 修改 APP 端文章状态和 ES 中索引库删除 APP 端文章成功");
        }else{
            //上架
            rabbitTemplate.convertAndSend(RabbitArticleDownOrUpConstants.ARTICLE_DOWN_OR_UP_EXCHANGE,
                    RabbitArticleDownOrUpConstants.UP_ROUTING_KEY,
                    wmNews.getArticleId());
            log.info("WmNews 上架状态修改后，通知 ApArticleConfig 修改 APP 端文章状态和 ES 中索引库新增 APP 端文章成功");
        }
    }

    /**
     * 运营管理端内容审核模块查询文章列表接口实现
     * @param wmNewsReviewDTO
     * @return
     */
    @Override
    public ResponseResult findWmNewsByStatus(WmNewsReviewDTO wmNewsReviewDTO) {
        //1.校验参数
            //1.校验分页参数
        wmNewsReviewDTO.checkParam();
            //2.设置查询数据
        wmNewsReviewDTO.setPage((wmNewsReviewDTO.getPage() - 1) * wmNewsReviewDTO.getSize());
        if(StringUtils.isNotBlank(wmNewsReviewDTO.getTitle())) {
            wmNewsReviewDTO.setTitle("%" + wmNewsReviewDTO.getTitle() + "%");
        }
        //2.查询文章
        List<WmNewsReviewVO> wmNews = wmNewsMapper.findWmNewsByStatus(wmNewsReviewDTO);
        Long total = wmNewsMapper.findCountByStatus(wmNewsReviewDTO);
        //3.响应结果
        PageResponseResult pageResponseResult = new PageResponseResult(wmNewsReviewDTO.getPage(), wmNewsReviewDTO.getSize(), total, wmNews);
        pageResponseResult.setHost(webSite);
        return pageResponseResult;
    }

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 运营管理端内容审核模块查询文章接口实现
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.校验参数
        if(id == null){
            log.error("运营管理端内容审核模块查询文章接口实现出现错误，错误原因: {}", "查询文章 id 为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章 id 不能为空");
        }
        //2.执行查询
        WmNews wmNews = this.getById(id);
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser == null){
            log.error("运营管理端内容审核模块查询文章接口实现出现错误, 错误原因: {}, 文章作者 id: {}", "查询文章的作者不存在", wmUser.getId());
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "查询文章不存在");
        }
        if(wmNews == null){
            log.error("运营管理端内容审核模块查询文章接口实现出现错误, 错误原因: {}, 文章 id: {}", "查询文章不存在", id);
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "查询文章不存在");
        }
        //3.响应结果
        ResponseResult responseResult = ResponseResult.okResult();
        WmNewsReviewVO wmNewsReviewVO = new WmNewsReviewVO();
        BeanUtils.copyProperties(wmNews, wmNewsReviewVO);
        wmNewsReviewVO.setAuthorName(wmUser.getName());
        responseResult.setHost(webSite);
        responseResult.setData(wmNewsReviewVO);
        return responseResult;
    }

    /**
     * 运营管理端-内容审核模块-审核
     * @param wmNewsReviewDTO
     * @return
     */
    @Override
    public ResponseResult reviewWmNews(WmNewsReviewDTO wmNewsReviewDTO) {
        //1.校验参数
        wmNewsReviewDTO.checkParam();
        if(wmNewsReviewDTO.getId() == null || wmNewsReviewDTO.getStatus() == null){
            log.error("运营管理端-内容审核模块-审核错误，错误原因: {}，文章 id: {}, 文章审核状态: {}", "文章 id 或 文章审核状态为空", wmNewsReviewDTO.getId(), wmNewsReviewDTO.getStatus());
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.PARAM_INVALID, "文章 id 和 文章审核状态不能为空");
        }
        WmNews wmNews = this.getById(wmNewsReviewDTO.getId());
        if(wmNews == null){
            log.error("运营管理端-内容审核模块-审核错误，错误原因: {}, 文章 id: {}", "审核文章不存在", wmNewsReviewDTO.getId());
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.DATA_NOT_EXIST, "审核文章不存在");
        }
        if(WmNews.Status.PUBLISHED.equals(wmNews.getStatus())){
            log.error("运营管理端-内容审核模块-审核错误，错误原因: {}, 文章 id: {}, 文章审核状态: {}", "文章已发布，状态不能修改", wmNewsReviewDTO.getId(),wmNewsReviewDTO.getStatus());
            CustomizeExceptionBuilder.builder(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章已发布，不能修改");
        }
        //2.执行审核
        wmNews.setStatus(wmNewsReviewDTO.getStatus());
        if(StringUtils.isNotBlank(wmNewsReviewDTO.getMsg())) {
            wmNews.setReason(wmNewsReviewDTO.getMsg());
        }
        wmNews.setSubmittedTime(new Date());
        this.updateById(wmNews);
        //定时发布文章
        timedPublishArticle(wmNews);
        //3.响应结果
        return ResponseResult.okResult();
    }

    /**
     * 生产者生产消息 - 定时文章发布
     * @param wmNews
     */
    private void timedPublishArticle(WmNews wmNews) {
        //1.计算 WmNews 发布时间
        long publish = wmNews.getPublishTime().getTime();
        long now = new Date().getTime();
        long ttl = publish - now <= 0 ? 0 : publish - now;
        //2.发送异步消息
        rabbitTemplate.convertAndSend(RabbitArticlePublishConstants.ARTICLE_PUBLISH_EXCHANGE,
                RabbitArticlePublishConstants.ARTICLE_PUBLISH_ROUTING_KEY,
                wmNews.getId(),
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setExpiration(String.valueOf(0));
                        return message;
                    }
                });
        log.info("ApArticle 定时发布消息投递成功，WmNews 信息: {}, 延时时长: {}", wmNews, ttl + "ms");
    }

    /**
     * 保存文章封面与素材的引用关系
     * @param wmNewsSaveDTO
     * @param wmNews
     * @param contentImages
     */
    private void resolveRelationForCover(WmNewsSaveDTO wmNewsSaveDTO, WmNews wmNews, List<String> contentImages) {
        List<String> coverImages = wmNewsSaveDTO.getImages();
        //1.判断文章的封面状态：【封面自动生成 -1】
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsSaveDTO.getType())){
            if(contentImages.size() > 2) {
                //1.1文章内容中的图片数 大于 2，将文章的封面状态设为 3(多图)，提取文章内容中前三张图片作为封面
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                coverImages = contentImages.stream().limit(WemediaConstants.WM_NEWS_MANY_IMAGE).collect(Collectors.toList());
            }else if(contentImages.size() > 1 && contentImages.size() <= 2){
                //1.2文章内容中的图片数 大于 1 小于等于 2，将文章的封面状态设为 1(单图)，提取文章内容中前一张图片作为封面
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                coverImages = contentImages.stream().limit(WemediaConstants.WM_NEWS_SINGLE_IMAGE).collect(Collectors.toList());
            }else {
                //1.3文章内容中的图片数 小于等于 1，将文章的封面状态设为 0(无图)
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                coverImages = null;
            }
            //2.重新修改文章信息：【文章封面类型】 +　【文章封面图片】
            if(coverImages != null){
                wmNews.setImages(convertImageStr(coverImages));
            }
            this.updateById(wmNews);
        }
        //3.保存文章封面与素材的关联关系
        if(coverImages != null){
            //3.1修正图片的 URL 格式
            coverImages = coverImages.stream().map(imageURL -> imageURL.replace(webSite, "")).collect(Collectors.toList());
            //3.2保存
            saveRelativeInfo(coverImages, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     * 保存文章内容与素材的引用关系
     * @param contentImages
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> contentImages, Integer newsId, Short type) {
        List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, contentImages));
        //3.1.3判断是否存在脏数据
        Map<String, Integer> relationMaterialInfo = wmMaterialList.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        List<Integer> wmMaterialIds = wmMaterialList.stream().map(material -> material.getId()).collect(Collectors.toList());
        for (String imagePath : contentImages) {
            if(!relationMaterialInfo.containsKey(imagePath)){
                CustomizeExceptionBuilder.builder(AppHttpCodeEnum.DATA_NOT_EXIST, "文章与图片的引用不匹配");
                //wmMaterialIds.remove(relationMaterialInfo.get(imagePath)); //不选择抛出异常，而是不记录引用关系
            }
        }
        wmNewsMapper.batchSaveRelation(wmMaterialIds, newsId, type);
    }

    /**
     * 解析文章内容中的图片数据
     * @param content
     */
    private List<String> resolveRelationForContent(String content) {
        //1.解析文章文本数据
        List<Map> contentData = JSON.parseArray(content, Map.class);
        //2.获取文章内容中所有图片的列表
        return contentData.stream().filter(element -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(element.get("type")))
                .map(element -> ((String) element.get("value")).replace(webSite, ""))
                .collect(Collectors.toList());
    }

    /**
     * 转换列表为字符串
     * @param imageList
     * @return
     */
    private String convertImageStr(List<String> imageList) {
        return imageList.stream().map(imageURL -> imageURL.replace(webSite,"")).collect(Collectors.joining(","));
    }
}
